package com.guigu.abo.config;

import com.github.pagehelper.PageInterceptor;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

@Configuration
@PropertySource("classpath:db.properties")
@MapperScan("com.guigu.abo.mapper")

public class MyBatisConfig {

    @Value("${jdbc.driver}")
    private  String driverClass;
    @Value("${jdbc.url}")
    private  String jdbcUrl;
    @Value("${jdbc.user}")
    private  String userName;
    @Value("${jdbc.password}")
    private  String usePassword;



    @Bean
    public DataSource getDataSuorce() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(this.driverClass);
        dataSource.setJdbcUrl(this.jdbcUrl);
        dataSource.setUser(this.userName);
        dataSource.setPassword(this.usePassword);

        return dataSource;
    }

    @Bean
    public SqlSessionFactoryBean getSession(DataSource dataSource){
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        PageInterceptor pageInterceptor = new PageInterceptor();
        sqlSessionFactoryBean.setPlugins(new Interceptor[]{pageInterceptor});
        /*设置别名*/
        sqlSessionFactoryBean.setTypeAliasesPackage("com.guigu.abo.pojo");

        return sqlSessionFactoryBean;
    }



}
